<template>
	<el-form ref="loginForm" :model="formData" :rules="formRules" label-width="0" size="large">
		<el-form-item prop="mobile">
			<el-input v-model="formData.mobile" clearable placeholder="请输入手机号">
				<template #prepend>
					<el-button :icon="Iphone" />
				</template>
			</el-input>
		</el-form-item>
		<el-form-item prop="code">
			<el-input v-model="formData.code" clearable placeholder="请输入短信验证码">
				<template #prepend>
					<el-button :icon="Unlock" />
				</template>
				<template #append>
					<div class="pl-2 pr-2">
						<SmsCode :count="60" :sendCodeApi="sendSmsCode" :apiParams="{scene:'user_login', mobile:formData.mobile}" />
					</div>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" style="width: 100%;" :loading="lock" round @click="handleLogin">登陆</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { ChannelEnum, LoginTypeEnum } from "@/enums/channelEnum";
import { Unlock, Iphone } from "@element-plus/icons-vue";
import { messageSuccess, messageError } from "@/utils/message";
import { isMobile } from "@/utils/validate";
import { login, sendSmsCode } from "@/api/login";
import useUserStore from "@/stores/user";

const props = defineProps({
	isAgreement: {
		type: Boolean,
		default: false,
	},
});

const userStore = useUserStore();

const loginForm = ref(null);

const formData = reactive({
	mobile: "",
	code: "",
	login_type: LoginTypeEnum.MOBILE,
	channel: ChannelEnum.PC,
});

const formRules = {
    mobile: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
            validator(rule: any, value: any, callback: any) {
                if (!isMobile(value)) {
                    callback(new Error("手机号不符合要求"));
                } else {
                    callback();
                }
            },
            trigger: ["change", "blur"],
        },
    ],
    code: [
        { required: true, message: "请输入短信验证码", trigger: "blur" },
        {
            min: 6,
            max: 6,
            message: "验证码长度应为6",
            trigger: ["change", "blur"],
        },
    ],
};

const { lock, apiCall: apiLogin } = useApiLock(login)
const handleLogin = async () => {
	await loginForm.value?.validate();
	if (!props.isAgreement) {
		messageError('确认已阅读并同意《服务协议》和《隐私政策》');
		return;
	}
	const data = await apiLogin(formData);
	userStore.login(data.token);
	messageSuccess('登录成功',() => {
		navigateTo("/")
	});
}

</script>
